<?php
/**
 * Memcache缓存引擎
 *
 * @since 1.0
 * @package if
 * @subpackage module.cache
 */
class IMemcacheCacheEngine extends IAbstractCacheEngine {
	private $settings = array();
	private $memcache;
	
	function init(array $settings = null) {
		if (is_array($settings)) {
			$this->settings = $settings;
		}
		$enabled = (bool)extension_loaded("memcache");
		if (!$enabled) {
			throw new ICacheException("memcache extension must be loaded in php.ini", 0x100068);
		}
		
		//settings
		$_setting = o("@cache.memcache");
		if ($settings) {
			$_setting = array_merge($_setting, $settings);
		}
		$this->settings = $_setting;
		
		//initilize
		$this->memcache = new Memcache();
		
		//添加服务器
		if (isset($this->settings["servers"])) {
			foreach ($this->settings["servers"] as $server) {
				if (is_array($server)) {
					$this->memcache->addServer(@$server["host"], @$server["port"], @$server["persistent"], @$server["weight"], @$server["timeout"], @$server["retry_interval"], @$server["status"], @$server["failure_callback"]);
				}
			}
		}
	}
	
	function clear($expired = false) {
		if (!$expired) {
			return $this->memcache->flush();
		}
		return true;
	}
	
	function delete($key) {
		return $this->memcache->delete($key);
	}
	
	function _entry($key) {
		$array = $this->memcache->get($key);
		if (!is_array($array)) {
			if ($array) {
				$this->delete($key);
			}
			return null;
		}
		
		$entry = new ICacheEntry($array);
		$entry->setEngine($this);
		if ($entry->expired()) {
			$this->delete($key);
			return null;
		}
		
		return $entry;
	}
	
	function _writeEntry(ICacheEntry $entry) {
		$array = $entry->asArray();
		return $this->memcache->set($entry->key(), $array, null, $entry->ttl());
	}
	
	function native() {
		return $this->memcache;
	}
}


?>